"""
任务管理器 - 智能工作计划作息规划表核心模块
"""

import json
import datetime
from typing import List, Dict, Any, Optional
from dataclasses import dataclass, asdict
import uuid

from config import PRIORITY_LEVELS, TIME_SLOTS
from ernie_model import ERNIETaskPlanner

@dataclass
class Task:
    """任务数据类"""
    id: str
    title: str
    description: str = ""
    urgency: int = 5  # 1-10
    importance: int = 5  # 1-10
    complexity: int = 5  # 1-10
    estimated_time: int = 30  # 分钟
    category: str = "其他"
    deadline: Optional[str] = None
    status: str = "待处理"  # 待处理、进行中、已完成
    created_at: str = ""
    optimal_time_slot: str = "上午"
    cognitive_load: str = "中"
    
    def __post_init__(self):
        if not self.created_at:
            self.created_at = datetime.datetime.now().isoformat()
        if not self.id:
            self.id = str(uuid.uuid4())[:8]
    
    @property
    def priority_score(self) -> int:
        """计算优先级分数"""
        return self.urgency + self.importance
    
    @property
    def priority_level(self) -> str:
        """获取优先级等级"""
        if self.urgency >= 7 and self.importance >= 7:
            return "紧急重要"
        elif self.urgency < 7 and self.importance >= 7:
            return "重要不紧急"
        elif self.urgency >= 7 and self.importance < 7:
            return "紧急不重要"
        else:
            return "不紧急不重要"

class TaskManager:
    """任务管理器"""
    
    def __init__(self):
        self.tasks: List[Task] = []
        self.ernie_planner = ERNIETaskPlanner()
        self.load_tasks()
    
    def add_task(self, title: str, description: str = "", **kwargs) -> Task:
        """添加新任务"""
        task = Task(
            id=str(uuid.uuid4())[:8],
            title=title,
            description=description,
            **kwargs
        )
        
        # 使用ERNIE模型分析任务
        analysis = self.ernie_planner.analyze_task_priority(
            task=title,
            context=description
        )
        
        # 更新任务属性
        if isinstance(analysis, dict) and 'error' not in analysis:
            task.urgency = analysis.get('urgency', task.urgency)
            task.importance = analysis.get('importance', task.importance)
            task.complexity = analysis.get('complexity', task.complexity)
            task.estimated_time = analysis.get('estimated_time', task.estimated_time)
            task.optimal_time_slot = analysis.get('optimal_time_slot', task.optimal_time_slot)
            task.cognitive_load = analysis.get('cognitive_load', task.cognitive_load)
            task.category = analysis.get('category', task.category)
        
        self.tasks.append(task)
        self.save_tasks()
        return task
    
    def update_task(self, task_id: str, **kwargs) -> Optional[Task]:
        """更新任务"""
        task = self.get_task(task_id)
        if task:
            for key, value in kwargs.items():
                if hasattr(task, key):
                    setattr(task, key, value)
            self.save_tasks()
        return task
    
    def delete_task(self, task_id: str) -> bool:
        """删除任务"""
        task = self.get_task(task_id)
        if task:
            self.tasks.remove(task)
            self.save_tasks()
            return True
        return False
    
    def get_task(self, task_id: str) -> Optional[Task]:
        """获取任务"""
        for task in self.tasks:
            if task.id == task_id:
                return task
        return None
    
    def get_tasks_by_status(self, status: str) -> List[Task]:
        """按状态获取任务"""
        return [task for task in self.tasks if task.status == status]
    
    def get_tasks_by_priority(self, priority_level: str) -> List[Task]:
        """按优先级获取任务"""
        return [task for task in self.tasks if task.priority_level == priority_level]
    
    def get_sorted_tasks(self, sort_by: str = "priority") -> List[Task]:
        """获取排序后的任务"""
        if sort_by == "priority":
            return sorted(self.tasks, key=lambda x: x.priority_score, reverse=True)
        elif sort_by == "deadline":
            return sorted(self.tasks, key=lambda x: x.deadline or "9999-12-31")
        elif sort_by == "created":
            return sorted(self.tasks, key=lambda x: x.created_at, reverse=True)
        elif sort_by == "time":
            return sorted(self.tasks, key=lambda x: x.estimated_time)
        else:
            return self.tasks
    
    def generate_daily_schedule(self, date: str = None, preferences: Dict = None) -> Dict[str, Any]:
        """生成每日作息规划表"""
        if not date:
            date = datetime.date.today().isoformat()
        
        # 获取待处理的任务
        pending_tasks = self.get_tasks_by_status("待处理")
        
        # 转换为字典格式供ERNIE模型使用
        tasks_data = []
        for task in pending_tasks:
            task_dict = asdict(task)
            task_dict['task'] = task.title  # 添加task字段供模型使用
            tasks_data.append(task_dict)
        
        # 使用ERNIE模型生成智能规划
        schedule = self.ernie_planner.generate_schedule(tasks_data, preferences)
        
        # 添加额外信息
        schedule["date"] = date
        schedule["total_tasks"] = len(pending_tasks)
        schedule["priority_distribution"] = self._get_priority_distribution(pending_tasks)
        
        return schedule
    
    def _get_priority_distribution(self, tasks: List[Task]) -> Dict[str, int]:
        """获取优先级分布"""
        distribution = {level: 0 for level in PRIORITY_LEVELS.keys()}
        for task in tasks:
            distribution[task.priority_level] += 1
        return distribution
    
    def get_productivity_stats(self) -> Dict[str, Any]:
        """获取生产力统计"""
        total_tasks = len(self.tasks)
        completed_tasks = len(self.get_tasks_by_status("已完成"))
        in_progress_tasks = len(self.get_tasks_by_status("进行中"))
        pending_tasks = len(self.get_tasks_by_status("待处理"))
        
        completion_rate = (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
        
        # 按类别统计
        category_stats = {}
        for task in self.tasks:
            category = task.category
            if category not in category_stats:
                category_stats[category] = {"total": 0, "completed": 0}
            category_stats[category]["total"] += 1
            if task.status == "已完成":
                category_stats[category]["completed"] += 1
        
        # 计算平均完成时间
        completed_task_times = [task.estimated_time for task in self.tasks if task.status == "已完成"]
        avg_completion_time = sum(completed_task_times) / len(completed_task_times) if completed_task_times else 0
        
        return {
            "total_tasks": total_tasks,
            "completed_tasks": completed_tasks,
            "in_progress_tasks": in_progress_tasks,
            "pending_tasks": pending_tasks,
            "completion_rate": round(completion_rate, 2),
            "category_stats": category_stats,
            "avg_completion_time": round(avg_completion_time, 2),
            "productivity_insights": self.ernie_planner.get_productivity_insights()
        }
    
    def save_tasks(self):
        """保存任务到文件"""
        try:
            tasks_data = [asdict(task) for task in self.tasks]
            with open("tasks.json", "w", encoding="utf-8") as f:
                json.dump(tasks_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存任务失败: {e}")
    
    def load_tasks(self):
        """从文件加载任务"""
        try:
            with open("tasks.json", "r", encoding="utf-8") as f:
                tasks_data = json.load(f)
                self.tasks = [Task(**task_data) for task_data in tasks_data]
        except FileNotFoundError:
            self.tasks = []
        except Exception as e:
            print(f"加载任务失败: {e}")
            self.tasks = []
    
    def export_schedule(self, schedule: Dict[str, Any], format: str = "json") -> str:
        """导出日程安排"""
        if format == "json":
            return json.dumps(schedule, ensure_ascii=False, indent=2)
        elif format == "text":
            text = f"📅 智能工作计划 - {schedule.get('date', '今天')}\n"
            text += "=" * 50 + "\n\n"
            
            for block in schedule.get("time_blocks", []):
                icon = "🔥" if block.get("priority", 0) > 14 else "⭐" if block.get("priority", 0) > 10 else "📝"
                text += f"{icon} {block['start_time']}-{block['end_time']} | {block['task']}\n"
                if block.get("category"):
                    text += f"   类别: {block['category']}\n"
                text += "\n"
            
            text += f"\n📊 统计信息:\n"
            text += f"总工作时间: {schedule.get('total_work_time', 0)}分钟\n"
            text += f"休息时间: {schedule.get('break_time', 0)}分钟\n"
            
            if schedule.get('optimization_tips'):
                text += f"\n💡 优化建议:\n"
                for tip in schedule['optimization_tips']:
                    text += f"• {tip}\n"
            
            return text
        else:
            return str(schedule)